<template>
    <div class="upload_container" v-loading="loading">
        <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="httpRequest">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <img v-if="!imageUrl && url" :src="url" class="avatar" />
            <el-icon size="30" v-if="!imageUrl && !url" class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </div>
</template>

<script>
import { defineComponent, ref, reactive, nextTick, onMounted, toRaw, toRefs, watch } from 'vue'
import { uploadImg } from "@/api/common.js";
export default defineComponent({
    props: {
        url: {
            type: String,
            default: () => ''
        },
        params: {
            type: String,
            default: () => ''
        },
        index: {
            type: Number,
            default: () => 0
        }
    },
    setup(props, { emit }) {
        const loading = ref(false)
        const imageUrl = ref('')
        const formData = new FormData();
        const beforeAvatarUpload = (file) => {
            console.log(file)
            loading.value = true
            formData.append("file", file, file.name);

            uploadImg(formData).then(response => {
                loading.value = false
                console.log(response, 'x')
                if (response) {
                    imageUrl.value = response.url
                    emit('success', response.url, props.index, props.params)
                }

            }).catch(err => {
                loading.value = false
                console.log(err, 'error--------------')
            })
        }
        const httpRequest = () => {

        }
        return {
            loading,
            imageUrl,
            beforeAvatarUpload,
            httpRequest
        }
    }
})
</script>
<style scoped lang='scss'>
.upload_container {
    border: 1px solid #bcb6b6;
    width: 100px;
    height: 100px;
    border-radius: 5px;
    position: relative;
    overflow: hidden;

    ::v-deep(.el-upload) {
        width: 100%;
        height: 100%;
        position: absolute;
    }

    .el-icon {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }

    .avatar {
        width: 100%;
        height: 100%;
    }

    ::v-deep(.el-loading-mask) {
        position: relative;
        top: 30px !important;
    }
}
</style>